'use strict';

const path = require('path');
const resolve = dir => path.resolve(__dirname, dir);
// 是否生产环境
const isProduction = process.env.NODE_ENV !== 'development';
// gzip压缩
const CompressionWebpackPlugin = require('compression-webpack-plugin');
// 打包分析
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

// 预渲染
const PrerenderSPAPlugin = require('prerender-spa-plugin');
const Renderer = PrerenderSPAPlugin.PuppeteerRenderer

// cdn
const cdn = {
	// 忽略打包的第三方库
	externals: {
		vue: 'Vue',
		vuex: 'Vuex',
		'vue-router': 'VueRouter',
		axios: 'axios',
	},
	// cdn引入的js
	js: [
		'https://cdn.bootcss.com/vue/2.6.11/vue.runtime.min.js',
		'https://cdn.bootcss.com/vue-router/3.1.2/vue-router.min.js',
		'https://cdn.bootcss.com/vuex/3.1.2/vuex.min.js',
		'https://cdn.bootcss.com/axios/0.19.2/axios.min.js',
		'https://cdn.bootcss.com/moment.js/2.24.0/moment.min.js'
	],
	css: [
		'https://at.alicdn.com/t/font_955790_lyw47q2agl.css',
		'https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.0.0/animate.min.css'
	]
};

// 基本配置
module.exports = {
	publicPath: './',
	outputDir: 'dist',
	assetsDir: 'static',
	indexPath: 'index.html',
	productionSourceMap: false,
	chainWebpack: (config) => {
		// // 打包分析
		// config.plugin('webpack-report').use(BundleAnalyzerPlugin, [
		// 	{
		// 		analyzerMode: 'static'
		// 	}
		// ])
		
		config.module
			.rule('swf')
			.test(/\.swf$/)
			.use('url-loader')
			.loader('url-loader')
			.tap((option) => {
				return {
					limit: 10000
				};
			});
		// 别名
		config.resolve.alias
			.set('@', resolve('src'))
			.set('@assets', resolve('src/assets'))
			.set('@components', resolve('src/components'))
			.set('@utils', resolve('src/utils'))
			.set('@api', resolve('src/request'))
			.set('@router', resolve('src/router'))
			.set('@store', resolve('src/store'))
			.set('@views', resolve('src/views'));
			
		config.plugin('copy').tap( args => {
			args[0][0].to = 'resource';
			return args;
		})
		// 移除prefetch
		config.plugins.delete('prefetch-index');
		// 移除preload
		config.plugins.delete('preload-index');
		if(isProduction){
			config.optimization.delete('splitChunks');
		}
		// cdn引入
		config.plugin('html').tap( args => {
			args[0].cdn = cdn;
			args[0].title = '黑河旅游官网';
			return args;
		})
	},
	// 
	configureWebpack: (config) => {
		// 忽略打包配置
		config.externals = cdn.externals;
		// 生产相关配置
		if(isProduction) {
			// gzip压缩
			const productionGzipExtensions = ['html', 'js', 'css'];
			config.plugins.push(
				new CompressionWebpackPlugin({
					filename: '[path].gz[query]',
					algorithm: 'gzip',
					test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'),
					threshold: 10240, // 只有大小大于该值的才会被处理
					minRatio: 0.8, // 只有压缩率小玉该值的资源才会被处理
					deleteOriginalAssets: false, // 删除原文件
				})
			);
			// 预渲染
			config.plugins.push(
				new PrerenderSPAPlugin({
					// 要求 给的webpack 输出应用程序的路径预渲染
					staticDir: path.join(__dirname, 'dist'),
					// 必填，需要渲染的路由
					routes: ['/','/cart','/profile','/login'],
					// 必填，要使用的实际渲染器，没有就不能预编译
					renderer: new Renderer({
						inject: {
							foo: 'bar'
						},
						// 渲染时，显示浏览器窗口，对调试用，true：不弹窗，false：弹窗
						headless: true,
						// 等待渲染，知道检测到指定元素
						// 例如：在项目入口使用 document.dispatchEvent(new Event('custom-render-trigger'))
						renderAfterDocumentEvent: 'render-event',
						// chromium 执行文件地址
						// executablePath: '/usr/bin/google-chrome'
					})
				})
			)
			// 抽离公共代码
			config.optimization = {
				// 分割代码
				splitChunks: {
					cacheGroups:{
						// 公共模块抽离
						common: {
							chunks: 'initial',
							minSize: 0,
							minChunks: 2, // 代码块最少被引用两次才会抽离
						},
						// 第三方库抽离
						vendor: {
							priority: 1, // 权重
							test: /node_modules/,
							chunks: 'initial',
							minSize: 0,
							minChunks: 2, // 分割前至少引用两次
						},
					}
				}
			};
		}
	},
	devServer: {
		overlay: {
			warings: false,
			errors: false,
		},
		open: false,
		host: '0.0.0.0',
		port: 8080,
		https: false,
		hot: true, // 热更新
		proxy: {
			'/v1': {
				target: process.env.VUE_APP_API_URL,
				changeOrigin: true, // 是否跨域
				secure: false,
				pathRewrite: {
					'^/v1': ''
				}
			}
		}
	},
	css: {
		extract: true,
		sourceMap: false,
		loaderOptions: {
			postcss: {
				plugin: [
					require('postcss-px2rem')({
						rootValue: 37.5,
						selectorBlackList: ['.ignore'], // 对css选择器进行过滤的数组，比如你设置为['fs']，那例如fs-xl类名，里面有关px的样式将不被转换 
						propList: ['*']
					})
				]
			},
			less: {
				prependData: `@import "~@/assets/less/variables.less";@import "~@/assets/less/base.less";@import "~@/assets/less/fun.less";@import "~@/assets/less/modules.less";`, // 引入公共scss模块
			}
		}
	}
}